//
//  HNSH_RYTools.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/2/16.
//

#import "HNSH_RYTools.h"

@implementation HNSH_RYTools

//融云建立连接
+ (void)connectWithToken:(NSString *)token {
    [[RCIMClient sharedRCIMClient] connectWithToken:token dbOpened:^(RCDBErrorCode code) {
                //消息数据库打开，可以进入到主页面
    } success:^(NSString *userId) {
        NSLog(@"连接成功==> %@",userId);
                //连接成功
        [HNSH_RYTools loadRongCloudFriendshipList];
    } error:^(RCConnectErrorCode errorCode) {
        NSLog(@"连接失败==> %ld",errorCode);
        if (errorCode == RC_CONN_TOKEN_INCORRECT) {
                    //token 非法，从 APP 服务获取新 token，并重连
        } else if(errorCode == RC_CONNECT_TIMEOUT) {
                    //连接超时，弹出提示，可以引导用户等待网络正常的时候再次点击进行连接
        } else {
                    //无法连接 IM 服务器，请根据相应的错误码作出对应处理
        }
    }];
    
    //连接状态监听 ==> 当 SDK 与融云服务器的连接状态发生变化时，开发者可通过下面代理方法监听 SDK 连接状态。
//    [[RCCoreClient sharedCoreClient] addConnectionStatusChangeDelegate:self];

}

//融云断开连接
+ (void)disconnect {
    [[RCIMClient sharedRCIMClient] disconnect:YES];
}

+ (void)updateUserCache:(HNSH_ChatFriendUserModel *)model {
    dispatch_async(dispatch_get_main_queue(), ^{
        RCUserInfo * userInfo = [[RCUserInfo alloc] init];
        userInfo.userId = model.user_id;
        NSString * displayName = model.display_name;
        userInfo.name = displayName.length ? displayName : model.name;
        userInfo.portraitUri = model.portrait;
        userInfo.extra = model.extra;
        [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:model.uid];
    });
}

//获取好友列表
+ (void)loadRongCloudFriendshipList {
    [HNSH_ChatNetServer requestRongCloudFriendshipListSuccess:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            NSArray *ary = [NSMutableArray arrayWithArray:[NSArray yy_modelArrayWithClass:[HNSH_ChatFriendModel class] json:responseObject.resultset]];
            for (HNSH_ChatFriendModel *model in ary) {
                [HNSH_RYTools updateUserCache:model.user];
            }
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//MARK: 获取群成员信息
+ (void)loadMembersWithGroupId:(NSString *)groupId {
    [HNSH_ChatNetServer requestRongCloudGroupMemberListWithGroupId:groupId pageNum:1 success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            NSArray *membersArray = [NSArray yy_modelArrayWithClass:HNSH_ChatFriendModel.class json:responseObject.resultset[@"list"]];
            for (HNSH_ChatFriendModel *model in membersArray) {
                [HNSH_RYTools updateUserCache:model.user];
            }
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

@end
